import axios from 'axios';

function num45Filter(amount, decimalCount = 2, decimal = '.', thousands = ',') {
    try {
        decimalCount = Math.abs(decimalCount);
        decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

        const negativeSign = amount < 0 ? '-' : '';
        let tempVal = Math.pow(10, 2);
        let i = parseInt(
            (amount = Math.abs(
                Number(Math.round(amount * tempVal) / tempVal) || 0
            ).toFixed(decimalCount))
        ).toString();
        let j = i.length > 3 ? i.length % 3 : 0;

        return (
            negativeSign +
            (j ? i.substr(0, j) + thousands : '') +
            i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousands) +
            (decimalCount
                ? decimal +
                  Math.abs(amount - i)
                      .toFixed(decimalCount)
                      .slice(2)
                : '')
        );
    } catch (e) {
        console.log(e);
    }
}

function checkStagePoint(manHour, estIncome, estCostRMB, stagePlans) {
    let filterStagePlans =
        stagePlans.filter(
            item => item.total === false || item.total === undefined
        ) || [];
    // 校验人月数
    if (!filterStagePlans) {
        return {
            isValid: false,
            errMsg: '请填写阶段点计划'
        };
    }
    let sumManHour = filterStagePlans
        .map(function(v) {
            return v.est_input_man_month;
        })
        .reduce(function(a, b) {
            return parseFloat(a || '0') + parseFloat(b || '0');
        }, 0);
    if (
        num45Filter(sumManHour, 2, '.', '') !== num45Filter(manHour, 2, '.', '')
    ) {
        console.log(
            num45Filter(sumManHour, 2, '.', ''),
            num45Filter(manHour, 2, '.', '')
        );
        return { isValid: false, errMsg: '阶段点投入总人月与工数预测不符' };
    }
    // 校验总投入
    let sumEstCost = filterStagePlans.length > 0 ? filterStagePlans
        .map(function(v) {
            return v.est_input_cost;
        })
        .reduce(function(a, b) {
            return parseFloat(a || '0') + parseFloat(b || '0');
        }, 0) : 0 ;
    if (
        num45Filter(sumEstCost, 2, '.', '') !==
        num45Filter(estCostRMB, 2, '.', '')
    ) {
        return { isValid: false, errMsg: '阶段点投入成本(RMB)与预测不符' };
    }
    // 校验总收入
    let sumEstIncome = filterStagePlans.length > 0 ? filterStagePlans
        .map(function(v) {
            return v.amount;
        })
        .reduce(function(a, b) {
            return parseFloat(a || '0') + parseFloat(b || '0');
        }) : 0 ;
    if (
        num45Filter(sumEstIncome, 2, '.', '') !==
        num45Filter(estIncome, 2, '.', '')
    ) {
        console.log(
            num45Filter(sumEstIncome, 2, '.', ''),
            num45Filter(estIncome, 2, '.', '')
        );
        return {
            isValid: false,
            errMsg: '阶段点不含税金额总数(RMB)与预测不符'
        };
    }
    return { isValid: true, errMsg: '' };
}

function checkImplDeptManager(incomeDistribution, departmentId) {
    let managerList = incomeDistribution
        .filter(item => item.implement_department_id !== departmentId)
        .map(item => {
            return item.manager_id;
        });
    for (const managerId of managerList) {
        if (managerId == '') {
            return {
                isValid: false,
                errMsg: '请选择工时管理员'
            };
        }
    }
    return {
        isValid: true,
        errMsg: ''
    };
}

function canEditForm( formId  , userLDAP  ) {
    const BACKEND_API = process.env.VUE_APP_PROJECT_REQUEST_HOST;
    return new Promise((resolve, reject) => {
        axios({
            url: `${BACKEND_API}/api/base/project/apply?id=${formId}` ,
            method: 'get'
        }).then(res => {
            if (res.data.code === 200) {
                let isCreator = res.data.creator_ldap === userLDAP;
                let isCollaborator = res.data.collaborators.find(x => x === userLDAP) !== undefined;
                if (isCreator || isCollaborator) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            }
            else {
                resolve(false);
            }
        });
    });
}

// function checkEditPermissions(formId, userLDAP) {
//     const canEdit = canEditForm(formId, userLDAP);
//     return canEdit;
// }

export { checkStagePoint, checkImplDeptManager, canEditForm };
